<title>角色管理</title>

<div class="layui-card layadmin-header">
    <div class="layui-breadcrumb" lay-filter="breadcrumb">
        <a lay-href="">主页</a>
        <a><cite>用户</cite></a>
        <a><cite>角色管理</cite></a>
    </div>
</div>

<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <div style="padding-bottom: 10px;">
                <button class="layui-btn layuiadmin-btn-role mybtn" data-type="batchdel">删除</button>
                <button class="layui-btn layuiadmin-btn-role mybtn" data-type="add">添加</button>
                <button class="layui-btn layuiadmin-btn-role mybtn" lay-filter="LAY-role-front-search" data-type="search"
                        style="float: right;margin: 0">
                    <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i>
                </button>
                <input onfocus="" style="width: 200px; float: right" type="text"
                       name="roleinfo"
                       value="" placeholder="请输入要查询的角色名称" autocomplete="off" class="layui-form layui-input">
            </div>

            <table id="LAY-user-back-role" lay-filter="LAY-user-back-role"></table>
            <script type="text/html" id="buttonTpl">
                {{#  if(d.check == true){ }}
                <button class="layui-btn layui-btn-xs">已审核</button>
                {{#  } else { }}
                <button class="layui-btn layui-btn-primary layui-btn-xs">未审核</button>
                {{#  } }}
            </script>
            <script type="text/html" id="table-useradmin-admin">
                <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit"><i
                        class="layui-icon layui-icon-edit"></i>编辑</a>
                <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del"><i
                        class="layui-icon layui-icon-delete"></i>删除</a>
            </script>
        </div>
    </div>
</div>

<script>
    layui.use(['form', 'table', 'admin', 'view'], function () {
        var $ = layui.$
            , form = layui.form
            , table = layui.table
            , admin = layui.admin
            , view = layui.view
        table.set({
            headers: { //通过 request 头传递
                Authorization: layui.data('layuiAdmin').Authorization
            }
        });
        table.render({
            elem: '#LAY-user-back-role'
            // , url: './json/useradmin/role.js' //模拟接口
            // , id: 'roletable'
            // , url: 'http://10.0.23.97:8195/portal/role/rolelist'
            , url: layui.setter.hostAddr +'/portal/role/rolelist'
            , cols: [[
                {type: 'checkbox', fixed: 'left'}
                , {field: 'roleId', width: 80, title: 'ID', sort: true}
                , {field: 'roleName', title: '角色名称'}
                , {field: 'describe', title: '描述信息'}
                , {title: '操作', width: 150, align: 'center', fixed: 'right', toolbar: '#table-useradmin-admin'}
            ]]
            // ,page: true
            , page: true
            , height: 'full-320'
            , limit: 10
            , text: '对不起，加载出现异常！'
        });

        table.on('tool(LAY-user-back-role)', function (obj) {
            var roledata = obj.data;
            if (obj.event === 'del') {
                layer.confirm('确定删除此角色？', function (index) {
                    var delobj = []
                    delobj.push(roledata.roleId)
                    $.ajax({
                        url: layui.setter.hostAddr +`/portal/role/role`,
                        dataType: 'json',
                        data: JSON.stringify(delobj),
                        async: false,
                        beforeSend: function (XMLHttpRequest) {
                            XMLHttpRequest.setRequestHeader("Authorization", layui.data('layuiAdmin').Authorization);
                            XMLHttpRequest.setRequestHeader("Content-Type", "application/json");
                        },
                        type: 'DELETE',
                        success: function (res) {
                            // console.log("删除结果====" + JSON.stringify(res))
                            doSuccess()
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            doFail()
                            //通常情况下textStatus和errorThrown只有其中一个包含信息
                            // console.log(textStatus);   //调用本次ajax请求时传递的options参数
                            // console.log(errorThrown);   //调用本次ajax请求时传递的options参数
                        }

                    })
                    obj.del();
                    layui.table.reload('LAY-user-back-role'); //重载表格
                    layer.close(index);
                });


            } else if (obj.event === 'edit') {
                // 获取个人权限数据，存储到sessionstorage
                $.ajax({
                    url: layui.setter.hostAddr +`/portal/role/role?roleId=${roledata.roleId}`,
                    dataType: 'json',
                    async: false,
                    // header:{
                    //     "Authorization":layui.data('layuiAdmin').Authorization
                    // },
                    beforeSend: function (XMLHttpRequest) {
                        XMLHttpRequest.setRequestHeader("Authorization", layui.data('layuiAdmin').Authorization);
                    },
                    type: 'GET',
                    success: function (res) {
                        doSuccess()
                        // console.log("初始数据====" + JSON.stringify(res))
                        layui.sessionData('personalPermission', {
                            key: "grantedMenuTree",
                            value: res.data.grantedMenuTree
                        })
                        layui.sessionData('personalPermission', {
                            key: "ungrantedMenuTree",
                            value: res.data.ungrantedMenuTree
                        })
                    },
                    error: function () {
                        doFail()
                    }

                })
                admin.popup({
                    title: '编辑新角色'
                    , area: ['1300px', '740px']
                    // , id: 'LAY-popup-user-add'
                    , success: function (layero, index) {
                        view(this.id).render('user/administrators/roleformedit', roledata).done(function () {
                            form.render(null, 'layuiadmin-form-role');

                            //监听提交
                            form.on('submit(LAY-user-role-submit)', function (data) {
                                 debugger
                                var editfield = data.field; //获取提交的字段

                                var editlpermission = layui.sessionData('layuiAdmin').editLeftPermissonData;
                                var editrpermission = layui.sessionData('layuiAdmin').editRightPermissonData;
                                editfield['grantedGnmkIds'] = editrpermission
                                console.log(JSON.stringify(editfield))
                                // editfield['unGrantedGnmkIds'] = editlpermission
                                // debugger
                                //提交 Ajax 成功后，关闭当前弹层并重载表格
                                // console.log("编辑角色的数据====" + JSON.stringify(editfield))
                                $.ajax({
                                    url: layui.setter.hostAddr +`/portal/role/role?roleId=${roledata.roleId}`,
                                    data: editfield,
                                    dataType: "json",
                                    async:false,
                                    beforeSend: function (XMLHttpRequest) {
                                        XMLHttpRequest.setRequestHeader("Authorization", layui.data('layuiAdmin').Authorization);
                                    },
                                    type: 'PUT',
                                    success: function (res) {
                                        // console.log("")
                                        doSuccess()
                                    },
                                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                                        //通常情况下textStatus和errorThrown只有其中一个包含信息
                                        // console.log(textStatus);   //调用本次ajax请求时传递的options参数
                                        // console.log(errorThrown);   //调用本次ajax请求时传递的options参数
                                        doFail()
                                    }
                                })
                                layui.table.reload('LAY-user-back-role'); //重载表格
                                layer.close(index); //执行关闭
                            });
                        });
                    }
                });
            }
        });

        var active = {
            batchdel: function () {
                var checkStatus = table.checkStatus('LAY-user-back-role')
                    , checkData = checkStatus.data  //得到选中的数据
                    , delobjs = []
                ;
                for (let i = 0; i < checkData.length; i++) {
                    delobjs.push(checkData[i].roleId)
                }
                // console.log(delobjs)
                if (checkData.length === 0) {
                    return layer.msg('请选择数据');
                }

                layer.confirm('确定删除吗？', function (index) {

                    //执行 Ajax 后重载

                    $.ajax({
                        url: layui.setter.hostAddr +`/portal/role/role`,
                        dataType: 'json',
                        data: JSON.stringify(delobjs),
                        async: false,
                        beforeSend: function (XMLHttpRequest) {
                            XMLHttpRequest.setRequestHeader("Authorization", layui.data('layuiAdmin').Authorization);
                            XMLHttpRequest.setRequestHeader("Content-Type", "application/json");
                        },
                        type: 'DELETE',
                        success: function (res) {
                            // console.log("删除结果====" + JSON.stringify(res))
                            doSuccess()
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            //通常情况下textStatus和errorThrown只有其中一个包含信息
                            console.log(textStatus);   //调用本次ajax请求时传递的options参数
                            console.log(errorThrown);   //调用本次ajax请求时传递的options参数
                            doFail()
                        }

                    })

                    table.reload('LAY-user-back-role');
                    // layer.msg('已删除');
                });
            },
            add: function () {
                //发请求获取所有权限数据，存储到sessionstorage中
                admin.popup({
                    title: '添加新角色'
                    , area: ['1300px', '740px']
                    // , id: 'LAY-popup-user-add'
                    , success: function (layero, index) {
                        view(this.id).render('user/administrators/roleform').done(function () {
                            form.render(null, 'layuiadmin-form-role');

                            //监听提交
                            form.on('submit(LAY-user-role-submit)', function (data) {
                                var field = data.field; //获取提交的字段
                                var lpermission = layui.sessionData('layuiAdmin').addLeftPermissonData;
                                var rpermission = layui.sessionData('layuiAdmin').addRightPermissonData;
                                field['grantedGnmkIds'] = rpermission
                                // field['unGrantedGnmkIds'] = lpermission
                                // console.log("权限数据===" + JSON.stringify(permission))
                                // console.log("添加角色===" + JSON.stringify(field))

                                //提交 Ajax 成功后，关闭当前弹层并重载表格
                                $.ajax({
                                    url: layui.setter.hostAddr +"/portal/role/role",
                                    data: field,
                                    dataType: "json",
                                    async: false,
                                    beforeSend: function (XMLHttpRequest) {
                                        XMLHttpRequest.setRequestHeader("Authorization", layui.data('layuiAdmin').Authorization);
                                    },
                                    type: 'POST',
                                    success: function (res) {
                                        console.log("")
                                        doSuccess()
                                    },
                                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                                        //通常情况下textStatus和errorThrown只有其中一个包含信息
                                        console.log(textStatus);   //调用本次ajax请求时传递的options参数
                                        console.log(errorThrown);   //调用本次ajax请求时传递的options参数
                                        doFail()
                                    }
                                })
                                layui.table.reload('LAY-user-back-role'); //重载表格
                                layer.close(index); //执行关闭
                            });
                        });
                    }
                });
            },
            search: function () {
                var roleVal = $("input[name='roleinfo']").val()

                //执行重载
                table.reload('LAY-user-back-role', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    , where: {
                        keyword:roleVal
                    }
                });
            }
        }
        $('.layui-btn.layuiadmin-btn-role').on('click', function () {
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });
    })

</script>